package com.spark.gaea.mvc.interceptors;

import com.google.common.collect.Maps;
import com.spark.gaea.mvc.MvcServerService;
import com.spark.gaea.mvc.utils.ParamUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

public class LoginStatusInterceptor extends HandlerInterceptorAdapter {
	@Autowired
	private MvcServerService mvcServerService;
	private Long misId;

	public Long getMisId() {
		return this.misId;
	}

	public void setMisId(final Long misId) {
		this.misId = misId;
	}

	@Override
	public boolean preHandle(final HttpServletRequest request, final HttpServletResponse response,
			final Object handler) {
		final String uri = request.getRequestURI().replace(request.getContextPath(), "");
		final String cmdStr = uri.substring(uri.lastIndexOf("/") + 1);
		if (cmdStr.equals("login") || cmdStr.equals("logout")) {
			return true;
		}
		final String sessionKey = ParamUtil.getCookie(request, "sessionKey");
		final Map<String, Object[]> map = Maps.newHashMap();
		map.put("sessionKey", new String[]{sessionKey});
		map.put("commandName", new String[]{this.getCmd(cmdStr)});
		return this.mvcServerService.verifyRequest(map);
	}

	@Override
	public void postHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler,
			final ModelAndView modelAndView) {
	}

	@Override
	public void afterCompletion(final HttpServletRequest request, final HttpServletResponse response,
			final Object handler, final Exception ex) {
	}

	public String getCmd(final String cmdStr) {
		if (this.getMisId() == null) {
			return cmdStr;
		}
		return this.getMisId() + ":" + cmdStr;
	}
}
